package com.sgj.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.sgj.common.constant.CartConstant;
import com.sgj.common.to.UserInfoTo;
import com.sgj.common.utils.R;
import com.sgj.common.vo.SkuInfoVo;
import com.sgj.gulimall.cart.feign.ProductFeignService;
import com.sgj.gulimall.cart.interceptor.CartInterceptor;
import com.sgj.gulimall.cart.service.CartService;
import com.sgj.gulimall.cart.vo.Cart;
import com.sgj.gulimall.cart.vo.Cart.CartItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author: Guoji Shen
 * @Date: 2021/9/13 9:52
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isBlank(res)) {
            // 购物车没有此商品
            // 将新商品添加到购物车
            CartItem cartItem = new CartItem();
            // 远程查询当前需要添加的商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            }, executor);

            // 远程查询sku组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);

            // 等待异步任务全部完成
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();
            log.info("[CartServiceImpl][addToCart] cartItem:{}", JSONObject.toJSONString(cartItem));
            // 将购物车信息存入redis
            cartOps.put(skuId.toString(), JSONObject.toJSONString(cartItem));
            return cartItem;
        }
        // 购物车已经有该商品，只需要修改数量即可
        CartItem item = JSONObject.parseObject(res, CartItem.class);
        item.setCount(item.getCount() + num);
        // 将购物车信息存入redis
        cartOps.put(skuId.toString(), JSONObject.toJSONString(item));
        return item;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        return JSONObject.parseObject(res, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        // 判断用户是否登陆
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();
        if (Objects.nonNull(userInfoTo.getUserId())) {
            // 用户已登陆
            // 登陆后的购物车rediskey
            String loginKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            // 未登录的购物车rediskey
            String notLoginKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            // 若临时购物车中有数据，则进行合并
            List<CartItem> tempCartItems = getCartItem(notLoginKey);
            if (!CollectionUtils.isEmpty(tempCartItems)) {
                // 临时购物车中有数据，进行合并
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                // 清空临时购物车的数据
                clearCart(notLoginKey);
            }
            // 登陆后的购物车数据(包含合并后临时购物车数据和购物车原有数据)
            cart.setItems(getCartItem(loginKey));
        } else {
            // 用户未登陆
            String notLoginKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            // 获取临时购物车所有购物项
            List<CartItem> cartItem = getCartItem(notLoginKey);
            cart.setItems(cartItem);
        }
        log.info("[CartServiceImpl][getCart] cart:{}", JSONObject.toJSONString(cart));
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSONObject.toJSONString(cartItem));
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSONObject.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (Objects.isNull(userInfoTo)) {
            return null;
        } else {
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItem = getCartItem(cartKey);
            List<CartItem> cartItemList = cartItem.stream()
                    .filter(item -> item.getCheck())
                    .map(item -> {
                        // 更新为最新价格
                        R r = productFeignService.getPrice(item.getSkuId());
                        String price = (String) r.get("data");
                        item.setPrice(new BigDecimal(price));
                        return item;
                    })
                    .collect(Collectors.toList());
            return cartItemList;
        }
    }

    /**
     * 获取要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (Objects.nonNull(userInfoTo.getUserId())) {
            // 用户已登陆
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            // 用户未登陆
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }

    /**
     * 获取临时购物车数据
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItem(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (!CollectionUtils.isEmpty(values) && values.size() > 0) {
            List<CartItem> collect = values.stream()
                    .map(obj -> JSONObject.parseObject((String) obj, CartItem.class))
                    .collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}